import { useRef, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { setCurrItemId, updateItem, showMenu } from "../../store/index";
function Parent(props) {
  const { children, style, id } = props;

  const currentcomponent = useSelector((state: any) => state.currentcomponent);

  const dispatcher = useDispatch();
  const editorWrapper = useRef(null);
  // 当前选种组件的Id
  const cId = useSelector((state: any) => state.currentCptId);
  const gap = {
    x: 0,
    y: 0,
  };
  const InformationRef = useRef(null);
  const [domLeft, setDomLeft] = useState(0);
  const [domTop, setDomTop] = useState(0);
  const [domWidth, setDomWidth] = useState(0);
  const [domHeight, setDomHeight] = useState(0);

  // 鼠标按下
  const mouseDown = (event) => {
    // 获取当前编辑器元素
    const currentElement = editorWrapper.current;
    if (currentElement) {
      // 获取当前元素的位置信息返回一个DOMRect对象
      const {
        left: x1,
        top: y1,
        width,
        height,
      } = currentElement.getBoundingClientRect();
      setDomWidth(width);
      setDomHeight(height);
      // 计算鼠标按下时鼠标位置与元素位置的差值
      gap.x = event.clientX - x1;
      gap.y = event.clientY - y1;
    }
    // 鼠标移动时间处理函数
    const mousemove = (e: any) => {
      // 计算新的位置信息
      const { left, top } = countLocation(e);
      setDomLeft(left);
      setDomTop(top);
      dispatcher(updateItem({ left, top }));
      InformationRef.current.style.visibility = "visible";
    };
    // 鼠标松开事件处理函数
    const mouseup = () => {
      // 清除鼠标移动
      InformationRef.current.style.visibility = "hidden";
      document.removeEventListener("mousemove", mousemove);
      document.removeEventListener("mouseup", mouseup);
    };
    // 添加鼠标移动和鼠标松开事件监听
    document.addEventListener("mousemove", mousemove);
    document.addEventListener("mouseup", mouseup);
    // 选中当前元素
    dispatcher(setCurrItemId(id));
    // 阻止事件冒泡
    event.stopPropagation();
  };
  // 封装函数计算组件元素的left和top
  const countLocation = (e) => {
    // 获取容易元素
    const container = document.querySelector(".edid_area");
    // 获取容器元素的位置信息
    const { left: xx, top: yy } = container.getBoundingClientRect();
    // 计算组件元素的left和top
    const left = e.clientX - xx - gap.x;
    const top = e.clientY - yy - gap.y;

    return {
      left,
      top,
    };
  };
  // 调整元素大小
  const startResize = (direction, e) => {
    //当前组件
    const currentElement = editorWrapper.current;
    //获取当前组件的视口的数据
    const { left, right, top, bottom } = currentElement.getBoundingClientRect();
    //mousemove  拉取移动
    const mousemove = (e) => {
      const size = caculateSize(direction, e, { left, right, top, bottom });
      //组件元素
      const { style } = currentElement;
      if (size) {
        style.width = size.width + "px";
        style.height = size.height + "px";
        if (size.left) {
          style.left = size.left + "px";
        }
        if (size.top) {
          style.top = size.top + "px";
        }
      }
      dispatcher(updateItem(size));
    };
    const mouseup = () => {
      document.removeEventListener("mousemove", mousemove);
      document.removeEventListener("mouseup", mouseup);
    };
    //触发鼠标移动事件  和鼠标得抬起事件
    document.addEventListener("mousemove", mousemove);
    document.addEventListener("mouseup", mouseup);
    //阻止事件冒泡
    e.stopPropagation();
  };
  // 定义一个函数，用于根据鼠标事件和位置信息计算出调整后的尺寸和位置(height,width,top,left)
  const caculateSize = (
    direction: any, // 调整方向
    e: { clientX: any; clientY: any }, // 鼠标事件对象
    positions: { left: any; right: any; top: any; bottom: any } // 初始位置信息
  ) => {
    const { clientX, clientY } = e; // 获取鼠标事件的坐标信息
    const { left, right, top, bottom } = positions; // 获取初始位置信息
    const container = document.querySelector(".edid_area"); // 获取包裹元素
    const { left: x1, top: y1 } = container.getBoundingClientRect();
    const rightWidth = clientX - left; // 计算右侧宽度
    const leftWidth = right - clientX; // 计算左侧宽度
    const bottomHeight = clientY - top; // 计算底部高度
    const topHeight = bottom - clientY; // 计算顶部高度
    const topOffset = clientY - y1; // 计算顶部偏移
    const leftOffset = clientX - x1; // 计算左侧偏移
    switch (direction) {
      // 左上角
      case "top-left":
        return {
          width: leftWidth,
          height: topHeight,
          top: topOffset,
          left: leftOffset,
        };
      //右上角
      case "top-right":
        return {
          width: rightWidth,
          height: topHeight,
          top: topOffset,
        };
      // 左下角
      case "bottom-left":
        return {
          width: leftWidth,
          height: bottomHeight,
          left: leftOffset,
        };
      //右下角
      case "bottom-right":
        return {
          width: rightWidth,
          height: bottomHeight,
        };
      default:
        break;
    }
  };

  return (
    <div
      className={`editItem ${id === cId ? "active" : ""} ${
        currentcomponent
          ? currentcomponent.classNameList.length
            ? currentcomponent.classNameList[
                currentcomponent.classNameList.length - 1
              ]
            : ""
          : ""
      } ${id === cId ? currentcomponent.PreviewAnimation : ""}`}
      onMouseDown={mouseDown}
      onContextMenu={(event) => {
        const center = document.querySelector(".editItem");
        const { left, top } = center.getBoundingClientRect();
        dispatcher(
          showMenu({ menuLeft: event.pageX - left, menuTop: event.pageY - top })
        );
        event.preventDefault();
      }}
      style={{ ...style, position: "absolute" }}
      ref={editorWrapper}
    >
      {children}
      <div className="Information_box" ref={InformationRef}>
        <div className="Information">
          <div>x:{domLeft.toFixed(0)}</div>
          <div>y:{domTop.toFixed(0)}</div>
          <div>w:{domWidth.toFixed(0)}</div>
          <div>h:{domHeight.toFixed(0)}</div>
        </div>
      </div>
      <div className="resizers">
        <div
          className="resizer top-left"
          onMouseDown={(e) => {
            startResize("top-left", e);
          }}
        ></div>
        <div
          className="resizer top-right"
          onMouseDown={(e) => {
            startResize("top-right", e);
          }}
        ></div>
        <div
          className="resizer bottom-left"
          onMouseDown={(e) => {
            startResize("bottom-left", e);
          }}
        ></div>
        <div
          className="resizer bottom-right"
          onMouseDown={(e) => {
            startResize("bottom-right", e);
          }}
        ></div>
      </div>
    </div>
  );
}

export default Parent;
